﻿using GiteePlugin.Core.Auth;
using GiteePlugin.Features.Activity;
using Microsoft.Extensions.DependencyInjection;
using Refit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GiteePlugin.Core
{
    /// <summary>
    /// 统一客户端  外部调用统一入口
    /// </summary>
    public class GiteeClient
    {

        private readonly IServiceProvider _serviceProvider;

        /// <summary>
        /// 动态通知功能模块入口
        /// </summary>
        public ActivityService Activity => GetService<ActivityService>();


        ///// <summary>
        ///// 仓库功能模块入口
        ///// </summary>
        //public RepoService Repositories => GetService<RepoService>();

        ///// <summary>
        ///// 用户功能模块入口
        ///// </summary>
        //public UserService Users => GetService<UserService>();

        ///// <summary>
        ///// Issue功能模块入口
        ///// </summary>
        //public IssueService Issues => GetService<IssueService>();

        public GiteeClient(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        //public 


        private T GetService<T>() where T : class
        {
            return _serviceProvider.GetService<T>()
             ?? throw new ModuleNotLoadedException(
                    $"{typeof(T).Name} 模块未加载，请在初始化时调用 features.Add{typeof(T).Name.Replace("Service", "")}()");

        }

        private T GetLazyService<T>() where T : class
        {
            var lazyService = new Lazy<T>(() =>
            {
                using var scope = _serviceProvider.CreateScope();
                var service = scope.ServiceProvider.GetService<T>();
                return service ?? throw new ModuleNotLoadedException(
                    $"{typeof(T).Name} 模块未加载，请在初始化时调用 features.Add{typeof(T).Name.Replace("Service", "")}()");
            });

            return lazyService.Value; // 获取 Lazy<T> 的值
        }
    }


    /// <summary>
    /// 模块未加载专用异常
    /// </summary>
    public class ModuleNotLoadedException(string message) : Exception(message)
    {
    }
}
